<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  createperform,
  deleteperform,
  updateperform,
  getPerformByPage,
  getPerformById
} from '@/api/perform'
import { getVenuesById, getAllVenues } from '@/api/venue'
import {
  Search,
  Refresh,
  View,
  CircleCheck,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const dialogVisible = ref(false)
const venueDialogVisible = ref(false)
const selectedVenue = ref(null)
const isEdit = ref(false) // 新增: 用于判断是新增还是编辑模式
const queryParams = reactive({
  name: ''
})

const pageNum = ref(1)
const pageSize = ref(10)
const ruleFormRef = ref()
const performForm = reactive({
  name: '',
  typeId: [],
  venueId: null,
  images: '',
  want: 0,
  openTime: '',
  performTime: '',
  performId: '',
  status: 1 // 新增: 状态字段
})

const rules = {
  name: [{ required: true, message: '请输入演出名称', trigger: 'blur' }],
  venueId: [{ required: true, message: '请选择演出场地', trigger: 'change' }],
  openTime: [{ required: true, message: '请选择开票时间', trigger: 'change' }],
  performTime: [
    { required: true, message: '请选择演出时间', trigger: 'change' }
  ],
  typeId: [{ required: true, message: '请选择演出类型', trigger: 'change' }]
}

const statusOptions = [
  { value: 1, label: '未演出', type: 'success' },
  { value: 2, label: '已结束', type: 'warning' }
]

const CityOptions = [
  { value: 1, label: '武汉' },
  { value: 2, label: '南昌' },
  { value: 3, label: '北京' },
  { value: 4, label: '保山' },
  { value: 5, label: '长春' },
  { value: 6, label: '长沙' },
  { value: 7, label: '常德' },
  { value: 8, label: '重庆' },
  { value: 9, label: '成都' },
  { value: 10, label: '大庆' }
]

const venueOptions = ref([
  { value: 1, label: '武汉体育中心' },
  { value: 2, label: '南昌国际体育中心' },
  { value: 3, label: '北京工人体育场' },
  { value: 4, label: '上海梅赛德斯文化中心' },
  { value: 5, label: '深圳湾体育中心' }
])

const typeMap = [
  { value: 1, label: '演唱会' },
  { value: 2, label: '音乐会' },
  { value: 3, label: 'LiveHouse' },
  { value: 4, label: '话剧' },
  { value: 5, label: '展览' },
  { value: 6, label: '展览' },
  { value: 7, label: '儿童' },
  { value: 8, label: '相声' },
  { value: 9, label: '脱口秀' }
]

const getHotType = (hot) => {
  if (hot >= 90) return 'danger'
  if (hot >= 70) return 'warning'
  return 'info'
}

const handleSizeChange = (val) => {
  pageSize.value = val

  fetchPerforms()
}

const handleCurrentChange = (val) => {
  pageNum.value = val

  fetchPerforms()
}

const handleSearch = async () => {
  pageNum.value = 1
  pageSize.value = 1

  const res = await getPerformById(queryParams.name)
  tableData.value = [
    {
      ...res.data,
      score: (Math.random() * 2 + 3).toFixed(1),
      hot: Math.floor(Math.random() * 40 + 60),
      status:
        new Date().getTime() <
          new Date(
            res.data.performTime[0],
            res.data.performTime[1] - 1,
            ...res.data.performTime.slice(2)
          ).getTime()
          ? '1'
          : '2'
    }
  ]
  total.value = res.data ? 1 : 0
}

const handleReset = () => {
  queryParams.name = ''

  pageNum.value = 1
  pageSize.value = 10

  fetchPerforms()
}
// 新增: 打开编辑弹窗
const handleEdit = (row) => {
  isEdit.value = true
  dialogVisible.value = true

  // 填充表单数据
  Object.assign(performForm, {
    performId: row.performId, // 保存ID用于更新
    name: row.name,
    typeId: row.typeId,
    venueId: row.venuesId,
    images: row.images,
    want: row.want,
    openTime: new Date(
      row.openTime[0],
      row.openTime[1] - 1,
      ...row.openTime.slice(2)
    ), // 转换为Date对象
    performTime: new Date(
      row.performTime[0],
      row.performTime[1] - 1,
      ...row.performTime.slice(2)
    ), // 转换为Date对象
    status: row.status
  })

  console.log(performForm)
}

// 新增: 删除确认
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该演出吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        loading.value = true
        await deleteperform(row.performId)
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        fetchPerforms() // 重新加载数据
      } catch (error) {
        console.error('Delete error:', error)
        ElMessage({
          type: 'error',
          message: '删除失败：' + error.message
        })
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

const createPerform = () => {
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(performForm, {
    name: '',
    typeId: [],
    venueId: null,
    images: '',
    want: 0,
    openTime: '',
    performTime: '',
    status: 1
  })
}

const viewVenueDetail = async (row) => {
  try {
    const response = await getVenuesById(row.venuesId)
    selectedVenue.value = response.data
    venueDialogVisible.value = true
  } catch (error) {
    console.error('Error fetching venue details:', error)
  }
}

const handleVenueDialogClose = () => {
  venueDialogVisible.value = false
  selectedVenue.value = null
}

const completeOrder = (id) => {
  console.log('Complete order:', id)
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const submitData = {
          name: performForm.name,
          typeId: performForm.typeId, // 因为checkbox-group返回数组，我们取第一个值
          venuesId: performForm.venueId,
          images: performForm.images,
          openTime: performForm.openTime.toISOString(),
          performTime: performForm.performTime.toISOString(),
          title: performForm.name, // 用name作为title
          performersIdList: [], // 如果需要可以添加演出者
          score: Math.floor(Math.random() * 30) + 70 // 模拟评分70-100
        }

        console.log(submitData)

        if (isEdit.value) {
          console.log({
            ...submitData,
            performId: performForm.performId
          })
          await updateperform({
            ...submitData,
            performId: performForm.performId
          })
        } else {
          await createperform(submitData)
        }

        ElMessage({
          type: 'success',
          message: isEdit.value ? '更新成功' : '创建成功'
        })
        dialogVisible.value = false
        fetchPerforms() // 重新加载数据
      } catch (error) {
        console.error('Submit form error:', error)
        ElMessage({
          type: 'error',
          message: '操作失败：' + error.message
        })
      } finally {
        loading.value = false
      }
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm(ruleFormRef.value)
}

const fetchPerforms = async () => {
  loading.value = true

  const res = await getPerformByPage(pageNum.value, pageSize.value)

  console.log(res.data.data)
  tableData.value = res.data.data.map((item) => ({
    ...item,
    score: (Math.random() * 2 + 3).toFixed(1),
    hot: Math.floor(Math.random() * 40 + 60),
    status:
      new Date().getTime() <
        new Date(
          item.performTime[0],
          item.performTime[1] - 1,
          ...item.performTime.slice(2)
        ).getTime()
        ? '1'
        : '2'
  }))
  total.value = res.data.total
  loading.value = false

  console.log(tableData.value)
}

const fetchVenues = async () => {
  const res = await getAllVenues()
  venueOptions.value = res.data.map((item) => {
    return {
      value: item.venuesId,
      label: item.venuesName
    }
  })
}

onMounted(() => {
  fetchPerforms()
  fetchVenues()
})
</script>

<template>
  <div class="order-list">
    <!-- Search Area -->
    <el-card class="search-card" shadow="hover">
      <el-form
        :inline="true"
        :model="queryParams"
        class="flex items-center flex-wrap gap-4"
      >
        <el-form-item label="演出:">
          <el-input v-model="queryParams.name" />
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-space>
        </el-form-item>
        <el-form-item style="position: relative; right: -550px">
          <el-space>
            <el-button type="primary" :icon="Plus" @click="createPerform"
              >创建</el-button
            >
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table-card mt-4" shadow="hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#f5f7fa' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column
          prop="name"
          label="演出名"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column label="演出场地" width="100" align="center">
          <template v-slot="scope">
            {{
              venueOptions.filter((item) => item.value === scope.row.typeId)[0]
                .label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="评分" width="100" align="center">
          <template #default="{ row }">
            <el-rate
              v-model="row.score"
              disabled
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="hot" label="热度" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getHotType(row.hot)">{{ row.hot }}°</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 1 ? 'success' : 'warning'"
              effect="dark"
            >
              {{ row.status === 1 ? '已结束' : '未演出' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="备注-标题"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="primary"
                link
                :icon="View"
                @click="viewVenueDetail(row)"
              >
                查看场地
              </el-button>
              <el-button
                type="primary"
                link
                :icon="Edit"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
              <template v-if="row.status === 2">
                <el-button
                  type="success"
                  link
                  :icon="CircleCheck"
                  @click="completeOrder(row.id)"
                >
                  完成订单
                </el-button>
              </template>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination mt-4">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Performance Form Modal -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑演出' : '创建演出'"
      width="70%"
      :before-close="handleCancel"
    >
      <el-form
        ref="ruleFormRef"
        :model="performForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="演出名称" prop="name">
          <el-input v-model="performForm.name" />
        </el-form-item>
        <el-form-item label="演出场地" prop="venueId">
          <el-select v-model="performForm.venueId" placeholder="请选择演出场地">
            <el-option
              v-for="venue in venueOptions"
              :key="venue.value"
              :label="venue.label"
              :value="venue.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开票-演出时间" required>
          <el-col :span="11">
            <el-form-item prop="openTime">
              <el-date-picker
                v-model="performForm.openTime"
                type="date"
                placeholder="选取日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="performTime">
              <el-time-picker
                v-model="performForm.performTime"
                placeholder="选取时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="演出类型" prop="typeId">
          <el-radio-group v-model="performForm.typeId">
            <el-radio
              v-for="item in typeMap"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 场地详情弹窗 -->
    <el-dialog
      v-model="venueDialogVisible"
      title="场地详情"
      width="50%"
      :before-close="handleVenueDialogClose"
    >
      <div v-if="selectedVenue" class="venue-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="场地名称">
            {{ selectedVenue.venueName }}
          </el-descriptions-item>
          <el-descriptions-item label="城市">
            {{ selectedVenue.city }}
          </el-descriptions-item>
          <el-descriptions-item label="具体位置">
            {{ selectedVenue.position }}
          </el-descriptions-item>
          <el-descriptions-item label="在售演出数">
            {{ selectedVenue.performs }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'PerformCenter'
}
</script>

<style scoped>
.order-list {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.text-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-card,
.table-card {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.search-card:hover,
.table-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
}

.table-card {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  padding: 16px 0;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
}

.venue-details {
  padding: 20px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}

:deep(.status-select) {
  width: 180px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
  height: 48px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-checkbox-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-rate) {
  display: inline-block;
}

:deep(.el-descriptions) {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

:deep(.el-descriptions__cell) {
  padding: 12px 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 20px;
}

@media screen and (max-width: 768px) {
  .order-list {
    padding: 16px;
  }
}
</style>
